// Methods related to links

import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { Links } from './links.js';

import { Areas } from '/imports/api/areas/areas.js';
import { Cates } from '/imports/api/cates/cates.js';

Meteor.methods({
  'links.insert'(name, url, area, cate, weight) {
    check(url, String);
    check(name, String);

    if (Links.find({name: name}).count() == 0) {
        

        if (Areas.find({name: area}).count() == 0) {
          Areas.insert({
            name: area,
            createdAt: new Date(),
          });
        }
        if (Cates.find({name: cate}).count() == 0) {
          Cates.insert({
            name: cate,
            area: area,
            createdAt: new Date(),
          });
        }
        return Links.insert({
          name,
          url,
          area,
          cate,
          weight,
          createdAt: new Date(),
        });



      }else{
        return "链接名已经存在"
      }
  },
  'links.delete'(id) {
    let link = Links.findOne(id);
    
    if (Links.find({cate: link.cate}).count() == 1) {
      Cates.remove({name: link.cate});
      
    }
    if (Links.find({area: link.area}).count() == 1) {
      Areas.remove({name: link.area});
    }
    return Links.remove(id);
  },
});


